﻿#include "cmd_process.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

#include <iostream>

CmdProcess::CmdProcess(const std::string &cmd, int waitTime)
	:cmd_(cmd), waitTime_(waitTime)
{

}

void CmdProcess::Start()
{
	int result = 0;
#ifdef _WIN32
	STARTUPINFO si;
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	PROCESS_INFORMATION pi;
	ZeroMemory(&pi, sizeof(pi));
	const char *localPath = "./";
	result = CreateProcess(nullptr, &cmd_[0], nullptr, nullptr, false, 0, nullptr, localPath, &si, &pi);
	//等待子进程结束后,才继续执行后续
	if (waitTime_ > 0)
	{
		if(waitTime_ > 9999999)
			WaitForSingleObject(pi.hProcess, INFINITE);
		else
			WaitForSingleObject(pi.hProcess, waitTime_);
	}

	process_ = pi.hProcess;
	thread_ = pi.hThread;
	
#else
	result = execl("/bin/sh", "sh", "-c", cmd_.c_str(), nullptr) != -1;
#endif

	//创建进程失败
	if (!result)
	{
		exit(-1);
	}
}

void CmdProcess::Stop()
{
#ifdef _WIN32
	if (process_)
	{
		CloseHandle(process_);
		process_ = nullptr;
	}
	if (thread_)
	{
		CloseHandle(thread_);
		thread_ = nullptr;
	}
#else
#endif
}

